<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\service;

use app\common\model\Category;
use app\common\model\Post;
use Xin\Support\Num;

class CategoryService{

	/**
	 * 获取列表
	 *
	 * @param array  $where
	 * @param string $order
	 * @param int    $page
	 * @param int    $limit
	 * @return array|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function lists(array $where = [], $order = 'sort asc', $page = 1, $limit = 10){
		$field = 'id,title,description,cover';
		return Category::where('status', 1)
			->where($where)
			->field($field)
			->order($order)
			->page($page, $limit)
			->select();
	}

	/**
	 * 获取分类列表 并进行文章统计
	 *
	 * @param array  $where
	 * @param string $order
	 * @param int    $page
	 * @param int    $limit
	 * @return \think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function listsWithStatistics(array $where = [], $order = 'sort asc', $page = 1, $limit = 10){
		return $this->lists($where, $order, $page, $limit)->each(function(Category $item){
			$postCount = Post::where('category_id', $item->id)->count();
			$postViewCount = Post::where('category_id', $item->id)->sum('view_count');

			$item['post_count'] = Num::formatSimple($postCount);
			$item['post_view_count'] = Num::formatSimple($postViewCount);

			return $item;
		});
	}
}
